<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <x-card>
        <div slot="content" class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48" >
              <a-col :span="10">
                <a-form-item
                  label="文档类别"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-select allow-clear placeholder="请选择文档类别" v-model="queryParam.code">
                    <a-select-option v-for="(item) in havStandardData" :key="item.id" :value="item.code">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="10">
                <a-form-item label="文档名称">
                  <a-input v-model="queryParam.name" allow-clear placeholder="请输入文档名称" />
                </a-form-item>
              </a-col>
              <a-col :span="4" class="search-buttons">
                <a-button type="primary" @click="handleClick" v-if="hasPerm('hdv_qhse_standard_page')">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetIt">重置</a-button>
              </a-col>
            </a-row>
            <a-row :gutter="48" >

            </a-row>
          </a-form>
        </div>
      </x-card>
      <a-card :bordered="false">
        <s-table
          ref="table"
          :columns="columns"
          :data="loadData"
          :alert="null"
          :rowKey="(record) => record.id"
          :rowSelection="null"
          bordered
        >
          <template slot="operator">
            <a-button type="primary" icon="plus" @click="$refs.addStandard.add()" v-if="hasPerm('hdv_qhse_standard_insert')">新增文档</a-button>
          </template>
          <span slot="action" slot-scope="text, record">
            <a
              :href="pdfUrl"
              @click="previewPdf(record)"
              target="_blank"
            >
              <a-button size="small" style="color:#389e0d;background-color: #f6ffed;border-color: #b7eb8f;">
                <a-icon type="eye" />
                预览
              </a-button>
            </a>
            <div class="pdf-overlay" @click="closePreview" v-if="null"></div>
            <embed
              v-if="null"
              :src="null"
              type="application/pdf"
              width="100%"
              height="100%"
              class="pdf-container" />
            <a-button size="small" style="color: #1d39c4;background-color: #f0f5ff;border-color: #adc6ff; margin-left: 5px;">
              <a @click="$refs.editStandard.edit(record)" v-if="hasPerm('hdv_qhse_standard_edit')">
                <a-icon type="edit" />
                编辑</a>
            </a-button>
            <a-popconfirm
              placement="topRight"
              title="确认删除？"
              @confirm="() => singleDelete(record)"
            >
              <a v-if="hasPerm('hdv_qhse_standard_delete')">
                <a-button size="small" style="color: #d4380d;background: #fff2e8;border-color: #ffbb96; margin-left: 5px;">
                  <a><a-icon type="delete" />删除</a>
                </a-button>
              </a>
            </a-popconfirm>
            <a
              @click="handleExport(record)"
              :loading="batchExportLoading"
            >
              <a-button size="small" style="color: #403463;background: #e6e6fd;border-color: #b29af9; margin-left: 5px;">
                <a-icon type="download" />
                下载
              </a-button>
            </a>
          </span>
        </s-table>
        <edit-standard ref="editStandard" @ok="handleOk" />
        <add-standard ref="addStandard" @ok="handleOk" />
        <!--<detail ref="detail" @ok="handleOk" />-->
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
  import { STable, XCard, XDown } from '@/components'
  import editStandard from './editStandard'
  import addStandard from './addStandard'
  import {
    getQHSEHavStandardList,
    searchQHSEHavStandard,
    // addQHSEHavStandard,
    // editQHSEHavStandard,
    deleteQHSEHavStandard
    // downloadQHSEHavStandard
  } from '@/api/modular/system/QHSEHavStandard'
  import { getDownloadPdf, getPreviewPdf } from '../../../api/modular/system/QHSEManager'
  export default {
    components: {
      XDown,
      XCard,
      STable,
      editStandard,
      addStandard
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        // 加载数据方法 必须为 Promise 对象
        loadData: (parameter) => {
          return searchQHSEHavStandard(Object.assign(parameter, this.queryParam)).then((res) => {
            console.log('表格数据', res.data)
            return res.data
          })
        },
        pdfData: null,
        // 表头
        columns: [
          {
            title: '序号',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '文档分类',
            dataIndex: 'standardCode'
          },
          {
            title: '文档名称',
            dataIndex: 'fileName'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: 330,
            scopedSlots: { customRender: 'action' }
          }
        ],
        queryParam: {
          code: '',
          name: ''
        },
        // pdfData: [],
        batchExportLoading: false,
        cFileName: '',
        havStandardData: [],
        filesTableData: [],
        defaultExpandedKeys: [],
        replaceFields: {
          children: 'children',
          title: 'title',
          key: 'workflowId',
          value: 'id',
          parentId: 'parentId'
        },
        pdfUrl: '',
        param: {},
        params: {},
        pagination: {
          total: 0,
          PageSize: 20,
          showTotal: total => `共 ${total} 条数据`,
          showSizeChanger: true,
          pageSizeOptions: ['5', '10', '15', '20']
          // onShowSizeChange: (current, pageSize) => this.pageSize = pageSize
        }
      }
    },
    created() {
      this.getQHSEHavStandardTree()
    },
    methods: {
      // 获取文档类别列表
      getQHSEHavStandardTree() {
        getQHSEHavStandardList(Object.assign(this.params)).then(res => {
          console.log('文档类别列表', res.data)
          this.treeLoading = false
          if (!res.success) {
            return
          }
          this.havStandardData = res.data
        })
      },
      // 查询文档内容
      searchQHSEHavStandard() {
        searchQHSEHavStandard(this.queryParam).then(res => {
          console.log('queryParam', this.queryParam)
          console.log('查询到的文档', res.data)
          // this.treeLoading = false
          if (!res.success) {
            return
          }
          this.filesTableData = res.data
        })
      },
      // 重置查询框内数据
      resetIt() {
        this.queryParam.code = ''
        this.queryParam.name = ''
      },
      // 单个删除
      singleDelete(record) {
        const param = [{ 'id': record.id }]
        this.deleteHavStandard(param)
      },
      // 删除方法
      deleteHavStandard(param) {
        console.log('param', param)
        deleteQHSEHavStandard(param)
          .then((res) => {
            if (res.success) {
              this.$message.success('删除成功')
              this.$refs.table.refresh()
            } else {
              this.$message.error('删除失败：' + res.message)
            }
          })
          .catch((err) => {
            this.$message.error('删除错误：' + err.message)
          })
      },
      // 点击查询按钮，刷新表格
      handleClick() {
        this.$refs.table.refresh(true)
      },
      // 新增/编辑/删除完刷新表格
      handleOk() {
        this.$refs.table.refresh()
      },
      previewPdf(record) { // 在此执行预览操作
        this.param.id = record.id
        this.param.name = record.fileName
        this.pdfUrl = null // 在预览之前先清空pdfUrl
        getPreviewPdf(Object.assign({}, this.param)) // 注意需要传递副本，以避免影响其他地方的param
          .then(response => {
            // 使用 Blob 构造函数创建一个 PDF 文件的对象 URL
            const fileBlob = new Blob([response.data], { type: 'application/pdf' })
            this.pdfUrl = URL.createObjectURL(fileBlob)
            if (this.pdfUrl) {
              // Open the PDF in a new tab
              window.open(this.pdfUrl, '_blank')
            }
          })
          .catch(error => {
            console.error('预览失败:', error)
          })
      },
      closePreview() {
        this.pdfData = '' // 清空 pdfData，隐藏预览内容
      },
      handleExport(record) { // 在此执行下载操作
        this.param.id = record.id
        this.param.name = record.fileName
        // console.log(this.param.name)
        this.getDownloadPdf()
      },
      getDownloadPdf() {
        getDownloadPdf(Object.assign(this.param)).then(response => {
          // 从response的headers中获取content-disposition字段，该字段包含服务器返回的文件名
          this.filename = this.param.name
          // 创建下载链接
          const downloadLink = document.createElement('a')
          downloadLink.href = window.URL.createObjectURL(response.data)
          // 设置下载链接的属性
          downloadLink.download = this.filename + '.pdf'
          downloadLink.target = '_blank'
          // 在下载链接的 click 事件处理程序中停止加载状态
          downloadLink.addEventListener('click', () => {
            this.batchExportLoading = false
          })
          // 触发下载
          try {
            downloadLink.click()
          } catch (error) {
            console.error('下载失败:', error)
            this.batchExportLoading = false
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
